package com.ogawa.base.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import androidx.core.content.ContextCompat.getSystemService
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.ogawa.base.Constant.Constant
import com.ska.skautils.utilcode.util.SkaUtils
import java.util.*
import kotlin.concurrent.schedule


class NetUtil: ConnectivityManager.NetworkCallback() {
    var TAG = "NetUtil_TAG__"
    var lastNetState =hasNet()
    var isFirst = false
    var curNetId:Int =0

    companion object{
       val instance = NetUtil()
   }
     fun hasNet():Boolean {
         LogUtils.e("hasConnect",isNetworkConnected(SkaUtils.getContext()))
        return isNetworkConnected(SkaUtils.getContext())
    }

    //网络连接成功
    override fun onAvailable(network: Network) {
        super.onAvailable(network)
        curNetId = network.hashCode()
        LogUtils.d("${TAG}网络连接成功===${network.hashCode()}")
        if(!lastNetState){
            lastNetState = hasNet()
            LogUtils.d("${TAG}连接状态===${lastNetState}==已连接")
            LiveEventBus.get(Constant.LIVE_EVENT_BUS_KEY_NET_STATE).post(true)
        }

    }


    //网络已断开连接
    override fun onLost(network: Network) {
        super.onLost(network)
        LogUtils.d("${TAG}网络已断开连接==+${network.hashCode()}===curNetId=${curNetId}")
         Timer().schedule(1000){
             if(curNetId==network.hashCode()){
                 LogUtils.d("${TAG}连接状态===${network.hashCode()}==已断开11")
                 curNetId =0
                 lastNetState = hasNet()
                 if(!lastNetState){
                     LogUtils.d("${TAG}连接状态===${network.hashCode()}==已断开22")
                     LiveEventBus.get(Constant.LIVE_EVENT_BUS_KEY_NET_STATE).post(false)

                 }

             }
         }





    }

    override fun onLosing(network: Network, maxMsToLive: Int) {
        super.onLosing(network, maxMsToLive)
//        LogUtils.d("${TAG}网络正在断开连接==${network.hashCode()}")

    }

    //无网络
    override fun onUnavailable() {
        super.onUnavailable()
//        LogUtils.d("${TAG}网络连接超时或者网络连接不可达")


    }

    //当网络状态修改（网络依然可用）时调用
    override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities)
        LogUtils.d("${TAG}当网络状态修改==${network.hashCode()}")
//
        // 表明此网络连接成功验证
        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                // 使用WI-FI

                LogUtils.d("${TAG}当前在使用WiFi上网${network}")
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                // 使用数据网络

                LogUtils.d("${TAG}当前在使用数据网络上网")
            } else{
                LogUtils.d("${TAG}当前在使用其他网络")
                // 未知网络，包括蓝牙、VPN等
            }
        }
    }

    //当网络连接属性发生变化时调用
    override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
        super.onLinkPropertiesChanged(network, linkProperties)
//        LogUtils.d("${TAG} 当网络连接属性发生变化==")


//        isMobileConnected()
    }

    /**
     * 判断网络是否连接
     */
    fun isNetworkConnected(context: Context?): Boolean {
        if (context != null) {
            val mConnectivityManager = context
                    .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                val mNetworkInfo = mConnectivityManager.activeNetworkInfo
                if (mNetworkInfo != null) {
                    return mNetworkInfo.isAvailable
                }
            } else {
                val network = mConnectivityManager.activeNetwork ?: return false
                val status = mConnectivityManager.getNetworkCapabilities(network)
                        ?: return false
                if (status.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
                    return true
                }
            }
        }
        return false
    }




    /**
     * 判断是否是数据网络连接
     */
     fun isMobileConnected(): Boolean {
        if (SkaUtils.getContext() != null) {
            val mConnectivityManager = SkaUtils.getContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                val mMobileNetworkInfo = mConnectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                if (mMobileNetworkInfo != null) {
                    return mMobileNetworkInfo.isAvailable
                }
            } else {
                val network = mConnectivityManager.activeNetwork ?: return false
                val status = mConnectivityManager.getNetworkCapabilities(network)
                        ?: return false
                if (status.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                    LogUtils.d("isMobileConnected     4GGGGG==")

                    return true
                }
                if (status.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                    LogUtils.d("isMobileConnected     WIFI==")

                    return true
                }
            }
        }
        return false
    }



    //获取网络启动
    fun getNetWorkStart(context: Context): Boolean {
        val connectivityManager = context //连接服务 CONNECTIVITY_SERVICE
                .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        //网络信息 NetworkInfo
        val activeNetworkInfo = connectivityManager.activeNetworkInfo
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
            //判断是否是wifi
            if (activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI) {
                //返回无线网络
                //  Toast.makeText(context, "当前处于无线网络", Toast.LENGTH_SHORT).show();
                return true
                //判断是否移动网络
            } else if (activeNetworkInfo.type == ConnectivityManager.TYPE_MOBILE) {
                //  Toast.makeText(context, "当前处于移动网络", Toast.LENGTH_SHORT).show();
                //返回移动网络
                return true
            }
        } else {
            //没有网络
            //  Toast.makeText(context, "当前没有网络", Toast.LENGTH_SHORT).show();
            return false
        }
        //默认返回  没有网络
        return false
    }


}